package com.yl.androidutilscenter.http

import com.yl.androidutilscenter.utils.LogUtils
import com.yl.androidutilscenter.utils.ext.isGsonFormat
import okhttp3.*

/**
 * @author YL
 * @description:打印log日志 拦截器
 * @date :2023/4/28 14:20
 */
class LogInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        // 新的请求,添加参数
        val request = chain.request()
        val builder1 = request.newBuilder()
        //添加header,创建新的请求
        val newBuilder = builder1
//            .addHeader("language", language)
            .build()
        val response = chain.proceed(request)

        val startTime = System.currentTimeMillis()
        val endTime = System.currentTimeMillis()
        val duration = endTime - startTime
        val mediaType = response.body()!!.contentType()
        val content = response.body()!!.string()
        LogUtils.i(tag = "retrofit", message = "----------Request Start----------------")
        val method = newBuilder.method()
        LogUtils.i(tag = "retrofit", message = newBuilder.toString())
        val sbHeader = StringBuilder()
        val headers = newBuilder.headers()
        headers.names().forEach {
            sbHeader.append(it + "=" + headers[it] + ",")
            sbHeader.append("\n")
        }
        LogUtils.i(tag = "retrofit", message = "| RequestHeaders:{")
        LogUtils.i(tag = "retrofit", message = "| $sbHeader}")
        LogUtils.i(tag = "retrofit", message = "| }")
        if (newBuilder.body() != null) {
            LogUtils.i(
                tag = "retrofit",
                message = "| RequestParams:${ParamsUtils.getRequestParams(newBuilder)}"
            )
        }
        if (content.isGsonFormat()) {
            LogUtils.json(tag = "retrofit", message = content)
        }

        LogUtils.i(
            tag = "retrofit",
            message = "----------Request End:" + duration + "毫秒----------"
        )
        return response.newBuilder()
            .body(ResponseBody.create(mediaType, content))
            .build()
    }


}